package com.apestech.framework.xml.sql.node;

import com.apestech.framework.json.JSONObject;
import com.apestech.framework.xml.pub.core.ElementUtil;
import com.apestech.framework.xml.sql.modul.SqlRule;
import org.dom4j.Element;

import java.util.List;

/**
 * @author hup
 * @create 2019-01-03-11:34
 */
public class NodeSqlRule extends ElementUtil{
    private Element node;
    private SqlRule sqlrule;
    public NodeSqlRule(Element node){
        this.node=node;
    }

    public void expain() throws Exception {
        List<?> list=node.content();
        int len=list.size();
        for(int i=0; i<len; i++){
            String scalss=list.get(i).getClass().getName();
            if(scalss.equals("org.dom4j.tree.DefaultElement")){
                Element eml=(Element) list.get(i);
                String nname=eml.getName().toUpperCase();
                if(sqlrule==null) sqlrule=new SqlRule();
                sqlrule.addTable(nname, getNodeAttr(eml).getJSONObject("attrNode"));
                getFields(eml, nname);
            }
        }
    }

    private void getFields(Element eml, String tabname) throws Exception {
        List<?> list=eml.content();
        int len=list.size();
        for(int i=0; i<len; i++){
            String scalss=list.get(i).getClass().getName();
            if(scalss.equals("org.dom4j.tree.DefaultElement")){
                Element e=(Element) list.get(i);
                String nname=e.getName().toUpperCase();
                String txt=e.getTextTrim();
                JSONObject m=getNodeAttr(e).getJSONObject("attrNode");
                if(m==null) m=new JSONObject();
                if(!"".equals(txt)) m.put("nb_sql", txt);
                sqlrule.addField(tabname, nname, m);
            }
        }
    }

    public SqlRule getSqlrule() {
        return sqlrule;
    }
}
